package lumingweihua.future.cn.lumingweihua.person;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.jpush.android.api.JPushInterface;
import lumingweihua.future.cn.baselibgxh.base.BaseActivity;
import lumingweihua.future.cn.baselibgxh.base.MyApplication;
import lumingweihua.future.cn.baselibgxh.network.AbstractRequest;
import lumingweihua.future.cn.baselibgxh.network.BeanRequest;
import lumingweihua.future.cn.baselibgxh.network.JsonElementRequest;
import lumingweihua.future.cn.baselibgxh.network.NetworkManager;
import lumingweihua.future.cn.baselibgxh.network.ReqTag;
import lumingweihua.future.cn.baselibgxh.network.entity.DefaultMamahaoServerError;
import lumingweihua.future.cn.baselibgxh.network.entity.MamaHaoServerError;
import lumingweihua.future.cn.baselibgxh.utils.Constant;
import lumingweihua.future.cn.baselibgxh.utils.SharedPreference;
import lumingweihua.future.cn.lumingweihua.MainActivity;
import lumingweihua.future.cn.lumingweihua.R;
import lumingweihua.future.cn.lumingweihua.WebViewActivity;
import lumingweihua.future.cn.lumingweihua.person.domain.LoginData;

/**
 * Created by Administrator on 2018/3/2.
 */

public class LoginActivity extends BaseActivity {
    private EditText et_phone;
    private EditText et_code;
    private TextView bt_ok;
    private TextView bt_check_code;

    @Override
    protected void initView() {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_login2);

        et_phone = (EditText) findViewById(R.id.et_phone);
        et_code = (EditText) findViewById(R.id.et_code);

        bt_ok = (TextView) findViewById(R.id.bt_ok);
        bt_ok.setOnClickListener(this);

        bt_check_code = (TextView) findViewById(R.id.bt_check_code);
        bt_check_code.setOnClickListener(this);

//        findViewById(R.id.iv_img).setOnClickListener(this);
        findViewById(R.id.tv_agreement).setOnClickListener(this);

        et_phone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

                //监听输入框内容，改变button状�??
                setButtonState(checkButtonIsOk());

                String phone = et_phone.getText().toString().trim();
                if (!TextUtils.isEmpty(phone) && isPhone(phone) && countDown == 60) {
                    bt_check_code.setClickable(true);
                    bt_check_code.setBackgroundResource(R.drawable.bt_common);
                } else {
                    bt_check_code.setClickable(false);
                    bt_check_code.setBackgroundResource(R.drawable.bt_gray);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
            }
        });
        et_code.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

                //监听输入框内容，改变button状态
                setButtonState(checkButtonIsOk());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
            }
        });

    }

    @Override
    protected void initData() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void processClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.bt_check_code:
                // 发�?�验证码
                if (isPhone(et_phone.getText().toString().trim())) {
                    requestCode(et_phone.getText().toString());
                    showProgressBar(null);
                }
                break;
            case R.id.bt_ok:
                //提交
                showProgressBar(null);
                requestRegister(et_phone.getText().toString(), et_code.getText().toString());
                break;
            case R.id.iv_img:
                finish();
                break;
            case R.id.tv_agreement:
                startActivity(new Intent(context, WebViewActivity.class).putExtra("url", Constant.URL_AGREEMENT));
                break;

            default:
                break;
        }
    }

    /**
     * 请求标识
     **/
    private final int REQUEST_LOGIN = 0;
    private final int REQUEST_CODE = 1;

    /**
     * 请求注册
     */
    private void requestRegister(String mobile, String code) {
        showProgressBar(null);

        BeanRequest<LoginData, DefaultMamahaoServerError> req = new BeanRequest<>(
                context,
                "",
                this, LoginData.class, false);


        req.setParam("apiCode", "_login_001");
        req.setParam("mobile", mobile);
        req.setParam("code", code);
        req.setParam("user_type", "2");

        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        addRequestQueue(req, REQUEST_LOGIN, new ReqTag.Builder().handleSimpleRes(true));
    }

    /**
     * 请求验证码
     */
    private void requestCode(String mobile) {
        showProgressBar(null);

        JsonElementRequest<DefaultMamahaoServerError> req = new JsonElementRequest<DefaultMamahaoServerError>(
                context, "", this);

        req.setParam("apiCode", "_sms_002");
        req.setParam("mobile", mobile);


        //获取token
        String token = NetworkManager.getInstance().getPostToken(req.getParam());
        req.setParam("token", token);

        addRequestQueue(req, REQUEST_CODE, new ReqTag.Builder().handleSimpleRes(true));
    }

    private boolean isPhoneOk;

    @Override
    protected void onResponseSuccess(ReqTag tag, Object data) {
        // TODO Auto-generated method stub
        super.onResponseSuccess(tag, data);
        switch (tag.getReqId()) {
            case REQUEST_LOGIN:
                LoginData d = (LoginData) data;
                d.setPhone(et_phone.getText().toString());
                JPushInterface.setAlias(getApplicationContext(), 1, d.getPhone());
                SharedPreference.saveToSP(context, "userToken", d.getUserToken());
                SharedPreference.saveToSP(context, "userId", d.getUserId());
                MyApplication.getInstance().setUserToken(d.getUserToken());
                MyApplication.getInstance().setUserId(d.getUserId());
                jumpToNextActivity(MainActivity.class, true);
                break;
            case REQUEST_CODE:
                handleCheckcode();
                break;

            default:
                break;
        }
    }

    @Override
    protected void onResponseFailure(ReqTag tag, MamaHaoServerError error,
                                     AbstractRequest.MamaHaoError clientError) {
        // TODO Auto-generated method stub
        super.onResponseFailure(tag, error, clientError);
    }

    private Timer sendCodeThread;// 验证码计时线�?
    private int countDown = 60;

    private void handleCheckcode() {
        // 发�?�验证码成功
        hideProgressBar(null);
        bt_check_code.setClickable(false);
        bt_check_code.setBackgroundResource(R.drawable.bt_gray);
        if (sendCodeThread == null)
            sendCodeThread = new Timer();
        sendCodeThread.schedule(new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                runOnUiThread(new Runnable() {
                    public void run() {
                        if (countDown == 0) {
                            // 计时完成
                            sendCodeThread.cancel();
                            sendCodeThread = null;
                            countDown = 60;
                            bt_check_code.setText(context
                                    .getString(R.string.send_again));
                            bt_check_code.setClickable(true);
                            bt_check_code.setBackgroundResource(R.drawable.bt_common);

                        } else {
                            bt_check_code.setText(countDown + " ″");
                            countDown--;
                        }
                    }
                });
            }
        }, 0, 1000);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (sendCodeThread != null) {
            sendCodeThread.cancel();
            sendCodeThread = null;
        }
    }

    private void setButtonState(boolean isEnabled) {
        if (isEnabled) {
            bt_ok.setEnabled(true);
            bt_ok.setBackgroundResource(R.drawable.bt_common);
        } else {
            bt_ok.setEnabled(false);
            bt_ok.setBackgroundResource(R.drawable.bt_gray);
        }
    }

    private boolean checkButtonIsOk() {
        String phone = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone))
            return false;
        String code = et_code.getText().toString().trim();
        if (TextUtils.isEmpty(code))
            return false;
        if (!isPhone(phone))
            return false;

        return true;
    }

    /**
     * 验证手机格式
     *
     * @param phone
     * @return
     */
    private boolean isPhone(String phone) {
        String regex = "^0?1[0-9]{10}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }
}
